// import { defineStore } from 'pinia'
import { getModels, getRightsByCat, getFnPrice } from '@/api/chat'
import cacheSetting from '@/cache-list/cache-setting'
import { invokeAPi } from '@/xz-fn'
// import { getRightsByCat } from '@/api/user'
// import queueReponseText from '@/utils/stream-reader-markdown'
// import { getLocalStorage, setLocalStorage } from '@/utils/storage'
// import { modelsSession, docModelsSession, righstMenuSession } from '@/cache-list/session-items'
// import { report } from '@/directives/report'

var __cache_chat_list = new Map()
function getMessageItem (message) {
  const item = {
    message_id: message.message_id,
    root: false,
    prev: null,
    next: null,
    parent_message_id: message.parent_message_id,
    role: message.role,
    target: message,
    brothers: [],
    renderIndex: 0
  }
  const tools = message.thoughts?.find((v) => v.tool === 'serper')
  if (tools) {
    item.tool = tools.tool
    item.observation = {}
    let observation = ''
    try {
      observation = JSON.parse(tools.observation).serper
    } catch (e) {
      observation = ''
    }
    item.observation[item.tool] = observation
  }
  if (item.role === 'assistant') {
    item.status = 'end'
    item.model = message.model_title
    item.type = ''
    item.like_status = message.like_status
    item.renderContent = []
    // queueReponseText.readWithStatic(message, item)
    item.target = message
    if (message.llm_thoughts && message.llm_thoughts.length) {
      item.target.thought = message.llm_thoughts.map((v) => v.thought).join('')
    }
  }
  return item
}

function combineMessagesToChatList (messages) {
  const list = new Map()
  const parentMap = new Map()

  const root = getMessageItem(messages[0])
  let cur = root
  list.set(root.message_id, root)
  for (let i = 1; i < messages.length; i++) {
    const item = getMessageItem(messages[i])
    list.set(item.message_id, item)
    const parentId = item.parent_message_id
    if (list.has(parentId)) {
      const node = list.get(parentId)
      if (!node.next) {
        item.prev = node
        node.next = item
      }
      if (item.parent_message_id === cur.message_id) {
        cur = item
      }
    }
    if (parentMap.has(parentId)) {
      parentMap.get(parentId).push(item.message_id)
    } else {
      parentMap.set(parentId, [item.message_id])
    }
  }
  parentMap.forEach((values) => {
    values.forEach((key) => {
      list.get(key).brothers = [...values]
    })
  })
  return { root, cur, list }
}

async function getSessionModels (type, force) {
  // if (force) {
  //   return getModels({ chat_type: type })
  // }
  // if (type === 'knowledge') {
  //   const data = await docModelsSession.getItem()
  //   if (data) return { data }
  //   const { data: val } = await getModels({ chat_type: type })
  //   if (val?.code === 200) docModelsSession.setItem(val)
  //   return { data: val }
  // }

  // const data = await modelsSession.getItem()
  // if (data) return { data }
  const { data: val } = await getModels({ chat_type: type })
  // if (val?.code === 200) modelsSession.setItem(val)
  return { data: val }
}
// 获取权益分组用来区分模型
async function getSessionRightsPid (pid) {
  // if (force) {
  //   return getRightsByCat({ pid: VUE_APP_PACKAGE_ID })
  // }
  // // const data = await righstMenuSession.getItem()
  // if (data) return { data }
  const { data: val } = await getRightsByCat({ pid })
  // if (val?.code === 200 && val?.data?.cat_list) righstMenuSession.setItem(val)
  return { data: val }
}

function combineModelsWithCategory (models = [], cats) {
  if (!cats.length) return models
  const rights = new Map()
  function findRightsitem (right_id) {
    if (rights.has(right_id)) return rights.get(right_id)
    let cat
    for (let i = 0; i < cats.length; i++) {
      cat = cats[i].right_list.find((child) => child.right_id === right_id)
      if (cat) break
    }
    if (cat) {
      rights.set(right_id, cat)
      return cat
    }
    return null
  }
  models.forEach((item) => {
    const cat = findRightsitem(item.right_id)
    if (cat) {
      item.right_cat_name = cat.name
    }
  })
  return models
}

function getDefaultRights (cats) {
  const models = ({
    'xz': ['10012', '10013', '10014', '10015'],
    'dll': ['80512', '80513', '80514', '80515']
  })[process.env.VUE_APP_NAME]
  if (!cats.length) return []
  const rights = []
  cats.map((cat) => {
    cat.right_list.map((item) => {
      const hasI = rights.find((v) => item.right_id === v.right_id)
      if (models.includes(item.right_id) && !hasI) {
        rights.push({
          right_id: item.right_id,
          name: item.name,
          rest_limit: item.c_limit_cond,
          limit_rate: item.c_limit_rate
        })
      }
    })
  })
  return rights
}

function getDefaultModel (type = 'chat', models) {
  if (type === 'chat') {
    const selected = cacheSetting.get('selectedChatModel')
    const selectedItem = models.find(
      (item) => item.model === selected
    )
    return selectedItem || models[0]
  }
  if (type === 'doc') {
    const selected = cacheSetting.get('selectedDocModel')
    const selectedItem = this.documentModels.find(
      (item) => item.model === selected
    )
    this.currentDocumentModel = selectedItem || this.documentModels[0]
    // return
    return selectedItem || this.documentModels[0]
  }
  return null
}

const state = {
  chatStore: {
    docSummarize: {
      status: '',
      type: '',
      code: 0,
      process: 0,
      documentModel: '',
      documentModelName: '',
      document: {},
      questions: []
    },
    showLimitSummarize: false,

    onlineSwitch: cacheSetting.get('onlineSwitch'),

    models: [], // 当前会话模型
    currentModel: {}, // 当前模型类型
    documentModels: [],
    currentDocumentModel: {}, // 当前文档模型类型
    showModels: false,

    isChating: false, // 是否正在聊天
    status: '', // 当前状态
    errorCode: null, // 当前错误状态码
    chatInput: '',
    // 上一条会话信息id
    prevConversionId: '',
    conversionId: '',
    newSession: 0, // 总的新消息数
    agent: null, // 智能体
    recommendAgents: [], // 推荐智能体
    defaultRights: [],

    modelsPriceMap: {}, // 模型计费价格
    dynamicToken: 0, // 消耗
    showDynamicToken: false
  }
}
const mutations = {
  SET_CHATSTORE (state, param) {
    state.chatStore = Object.assign({}, state.chatStore, param)
  },
  SET_CHATSTORE_DOC (state, param) {
    state.chatStore.docSummarize = Object.assign({}, state.chatStore.docSummarize, param)
  },
  SET_MODELS_PRICE (state, obj) {
    state.chatStore.modelsPriceMap = obj
  },
  SET_DYNAMICTOKEN (state, val) {
    state.chatStore.dynamicToken = val
  },
  SET_SHOWDYNAMICTOKEN (state, val) {
    state.chatStore.showDynamicToken = val
  }
}
const actions = {
  setChatStore ({ commit }, obj) {
    commit('SET_CHATSTORE', { ...obj })
  },
  setDocSummarize ({ commit }, obj) {
    commit('SET_CHATSTORE_DOC', { ...obj })
  },

  setOnlineSwitch ({ commit }, v) {
    commit('SET_CHATSTORE', { onlineSwitch: v })
    cacheSetting.set('onlineSwitch', v)
    // report(v ? 125 : 124)
  },
  setDocumentSummarize ({ commit, state }, { status, type, data, code, errMsg }) {
    const doc = {}
    if (type) doc.type = type
    doc.status = status
    if (data) doc.document = { ...state.chatStore.docSummarize.document, ...data }
    if (code) doc.code = code
    doc.errMsg = errMsg
    // console.log('setDocumentSummarize.doc', doc)
    commit('SET_CHATSTORE_DOC', doc)
  },
  resetDocumentSummarize ({ commit }) {
    const doc = {
      document: {},
      status: '',
      questions: [],
      code: 0,
      type: ''
    }
    commit('SET_CHATSTORE_DOC', doc)
    commit('SET_CHATSTORE', { conversionId: '' })
  },
  async getModels ({ commit, rootState }, { type, force }) {
    const { data } = await getSessionModels(type, force)
    const { models, code } = (data || {})
    if (code !== 200) return
    if (type === 'knowledge' && models && models.length) {
      const documentModels = models
      const currentDocumentModel = models[0]
      commit('SET_CHATSTORE', { documentModels, currentDocumentModel })
      return
    }
    let pkg_id = process.env.VUE_APP_PACKAGE_ID
    if (rootState.system.info.appID === 111) {
      pkg_id = '20000'
    }
    const { data: cats } = await getSessionRightsPid(pkg_id)
    const defaultRights = getDefaultRights(cats?.data?.cat_list || [])
    const modelList = combineModelsWithCategory(models || [], cats?.data?.cat_list || [])
    // modelList[2].thinking_enabled = false
    const currentModel = getDefaultModel('chat', modelList)
    invokeAPi('AiModelSwitch', currentModel.model)
    commit('SET_CHATSTORE', { currentModel, defaultRights, models: modelList })
  },
  setCurrentModel ({ commit, state }, { model, type }) {
    if (state.chatStore.docSummarize.status !== '' || type === 'doc') {
      commit('SET_CHATSTORE', { currentDocumentModel: model })
    } else {
      commit('SET_CHATSTORE', { currentModel: model })
      cacheSetting.set('selectedChatModel', model.model)
      invokeAPi('AiModelSwitch', model.model)
    }
  },
  setHistoryMessage ({ commit }, { messages, conversation_id, callback }) {
    commit('SET_CHATSTORE', { conversionId: conversation_id || '' })
    if (messages.length === 0) {
      commit('SET_CHATSTORE', { isChating: true })
      return
    }
    const { root, cur, list } = combineMessagesToChatList(messages)
    __cache_chat_list = list
    commit('SET_CHATSTORE', {
      status: 'end',
      conversionId: cur.target?.conversation_id,
      isChating: true
    })
    callback && callback(root, cur)
  },
  resetChat ({ commit }) {
    commit('SET_CHATSTORE', {
      isChating: false,
      conversionId: '',
      status: '',
      agent: null
    })
    __cache_chat_list.clear()
  },
  reset ({ commit, dispatch }) {
    dispatch('resetChat')
    commit('SET_CHATSTORE', { isChating: false })
    commit('SET_CHATSTORE_DOC', {
      status: '',
      document: {},
      questions: [],
      documentModel: ''
    })
  },
  updateNodesBrothers ({ commit, dispatch }, { node, messageId }) {
    if (!node) return
    // 添加自身
    if (node.message_id && !node.brothers?.includes(node.message_id)) {
      node.brothers.push(node.message_id)
    }
    node.brothers.push(messageId)
    node.brothers.forEach((key) => {
      if (key === node.message_id) return
      const item = __cache_chat_list.get(key)
      if (item) {
        item.brothers = [...node.brothers]
        item.renderIndex = item.brothers.length - 1
      }
    })
  },
  setToCacheItem ({ commit }, item) {
    __cache_chat_list.set(item.message_id, item)
  },
  getToCacheItem ({ commit }, { val, callback }) {
    const next = __cache_chat_list.get(val)
    callback && callback(next)
  },
  async getFnPrice ({ commit }) {
    const { data } = await getFnPrice()
    const { data: { list } = {}, code } = (data || {})
    if (code !== 200) return
    const obj = {}
    list.forEach(({ fn_id, fn_num, fn_unit_name, price, price_unit_name }) => {
      let fn_num_text = fn_num
      if (fn_num === 1000) {
        fn_num_text = '1千'
      }
      obj[fn_id] = {
        fn_num,
        fn_num_text,
        fn_unit_name,
        price,
        price_unit_name
      }
    })
    commit('SET_MODELS_PRICE', obj)
  },
  setDynamicToken ({ commit }, val) {
    commit('SET_DYNAMICTOKEN', val)
    if (val) {
      commit('SET_SHOWDYNAMICTOKEN', true)
      setTimeout(() => {
        commit('SET_SHOWDYNAMICTOKEN', false)
      }, 1500)
    }
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
